package com.apache.client.common;

import com.apache.api.api.IAuthentication;
import com.apache.client.UctCoreClient;
import com.apache.oscache.OsCacheManager;
import com.apache.passport.common.XmlWhiteUtils;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.Role;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2021/2/1
 */
public class DefaultIAuthentication implements IAuthentication {

    private Map<String, ArrayList<String>> whiteMap = new HashMap<String, ArrayList<String>>();

    @Override
    public boolean aouthSecurity(Object user, HttpServletRequest request, HttpServletResponse response, String userRoles, String userTypes) {

        /*String sysCode = String.valueOf(request.getAttribute("sys-ename-code"));
        if(unlockPath(request.getServletPath(), sysCode)){//白名单验证
            return true;
        }*/
        String tokenId = StringUtil.getTokenId(request);
        if(StrUtil.isNull(tokenId)){
            return false;
        }
        LoginUser loginUser = (LoginUser)OsCacheManager.getInstance().getLoginUser(tokenId);
        if(null == loginUser) {
            loginUser = setLoginUser(request, tokenId);
            OsCacheManager.getInstance().putLoginUser(tokenId, loginUser);
        }
        if(null == loginUser){
            return false;
        }
        if("1".equals(loginUser.getSysFlag())){
            return true;
        }
        if(StrUtil.isNotNull(userTypes)){//验证用户类型
            List<String> list = Arrays.asList(userTypes.split(","));
            if(list.contains(loginUser.getUserType())){
                return true;
            }
        }
        return canAccess(loginUser, request.getServletPath(), userRoles);
    }

    /**
     * 权限过滤
     * @param loginUser
     * @param path
     */
    private boolean canAccess(LoginUser loginUser, String path,String userRoles) {
        String superUser = (StrUtil.doNull(ConfigUtil.getInstance().getValueByKey("uct_supper_user"), ""));
        if(StrUtil.isNotNull(superUser)){//判断是否指定的管理员
            List<String> us = Arrays.asList(superUser.split(","));
            if(us.contains(loginUser.getUserEname())){
                return true;
            }
        }
        if(StrUtil.isNotNull(userRoles)) {//判断用户角色是否符合
            List<String> list = Arrays.asList(userRoles.split(","));
            Object objRoles = OsCacheManager.getInstance().getCustomerUser(loginUser.getUser().getUserId());
            if(null == objRoles){
                return false;
            }
            List<Map> roles = (List)objRoles;
            for(int i=0;i<roles.size();i++) {
                Map<String,String> role = roles.get(i);
                if(list.contains(role.get("roleEname"))) {
                    return true;
                }
            }
        }
        Map<String, Act> acts = loginUser.getActMap();
        if (null != acts && !acts.isEmpty()) {//判断是否对此请求授权
            for (String key : acts.keySet()) {
                Act act = acts.get(key);
                if (StrUtil.isNotNull(act.getActUrl())) {
                    String str[] = act.getActUrl().split(",");
                    for (int i = 0; i < str.length; i++) {
                        if (path.indexOf(str[i]) > -1 || path.indexOf(act.getFullEname()) > -1) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取当前登录用户信息
     */
    private LoginUser setLoginUser(HttpServletRequest request, String tokenId) {
        LoginUser loginUser = UctCoreClient.getLoginUserFromUserCenterSso("", tokenId);
        if (!StrUtil.isEmpty(loginUser)) {
            request.getSession().setAttribute("sysUser", loginUser.getSysFlag());
            request.getSession().setAttribute("loginUser", loginUser);//获取session中信息
            List<Role> roles = PBOSSOTools.getRolesForLoginUser(request);//获取用户角色列表
            if (!ToolsUtil.isEmpty(roles)) {
                OsCacheManager.getInstance().putCustomerUser(loginUser.getUser().getUserId(),roles);
            }
        }
        return loginUser;
    }

    private boolean unlockPath(String path, String sysCode) {
        if(whiteMap.isEmpty()) {
            XmlWhiteUtils.getInstance().deWhiteXml(whiteMap, sysCode);
        }
        ArrayList<String> whiteUrl = (ArrayList<String>) whiteMap.get("whiteUrl");
        ArrayList<String> whiteParadigm = (ArrayList<String>) whiteMap.get("whiteParadigm");
        int wp = whiteParadigm.size();
        if (path.length() > 1) {
            if (whiteUrl.contains(path)) {
                return true;
            }
            for (int i = 0; i < wp; i++) {
                if ((whiteParadigm.get(i)).contains("*")) {
                    String wdir = (whiteParadigm.get(i)).replace("*", "");
                    int s = path.indexOf(wdir);
                    if (s == 0) {
                        return true;
                    }
                } else if (!"".equals(whiteParadigm.get(i))) {
                    int s = path.indexOf(whiteParadigm.get(i));
                    if (s == 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
